package com.ctshk.rpc.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.OperationLogDTO;
import com.ctshk.rpc.system.dto.StockScenicAreaDTO;
import com.ctshk.rpc.system.dto.StockScenicAreaPhotoDTO;
import com.ctshk.rpc.system.dto.StockScenicQueryAreaPhotoDTO;
import com.ctshk.rpc.system.entity.*;
import com.ctshk.rpc.system.mapper.*;
import com.ctshk.rpc.system.req.*;
import com.ctshk.rpc.system.service.IStockScenicAreaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author xuhui
 * @since 1/29/2021
 */
@DubboService
public class StockScenicAreaServiceImpl implements IStockScenicAreaService {

    @Autowired
    StockScenicAreaMapper stockScenicAreaMapper;

    @Autowired
    StockScenicAreaPhotoMapper stockScenicAreaPhotoMapper;

    @Autowired
    OperationLogMapper operationLogMapper;

    volatile  boolean addFailed=false;

    /**
     * 根据地区名称查询图片
     *
     * @param stockScenicAreaPhotoListReq 入参
     * @return 所有图片
     */
    @Override
    public PageResponse<StockScenicQueryAreaPhotoDTO> queryAreaPhoto(StockScenicAreaPhotoListReq stockScenicAreaPhotoListReq) {
        IPage<StockScenicQueryAreaPhotoDTO> page = new Page<>(stockScenicAreaPhotoListReq.getPageNo(),stockScenicAreaPhotoListReq.getPageSize());
        page = stockScenicAreaPhotoMapper.queryAreaPhotoList(stockScenicAreaPhotoListReq,page);
        PageResponse<StockScenicQueryAreaPhotoDTO> result = new PageResponse<>(page.getRecords(),page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }


    @Override
    public PageResponse<StockScenicAreaDTO> areaList(StockScenicAreaListReq stockScenicAreaListReq, TokenUser currentUser) {
        QueryWrapper<StockScenicArea> areaWrapper = new QueryWrapper<>();
        if(!StockScenicAreaListReq.searchAll)
        areaWrapper.like("area_name", stockScenicAreaListReq.getAreaName());
        StockScenicAreaListReq.searchAll=false;
        areaWrapper.eq("is_deleted",0);
        List<StockScenicArea> stockScenicAreaList= stockScenicAreaMapper.selectList(areaWrapper);
        List<StockScenicAreaDTO> stockScenicAreaDTOList=new ArrayList<>();
        stockScenicAreaList.forEach(i -> {
            StockScenicAreaDTO stockScenicAreaDTO=EntityUtil.copy(i,StockScenicAreaDTO.class);
            QueryWrapper<StockScenicAreaPhoto> photoNumWrapper=new QueryWrapper<>();
            photoNumWrapper.eq("stock_id",i.getId());
           Integer imgNums= stockScenicAreaPhotoMapper.selectCount(photoNumWrapper);
            stockScenicAreaDTO.setImgNums(imgNums);
            stockScenicAreaDTOList.add(stockScenicAreaDTO);
        });
        Page<StockScenicArea> iPage=new Page<>(stockScenicAreaListReq.getPageNo(), stockScenicAreaListReq.getPageSize());
        iPage = stockScenicAreaMapper.selectPage(iPage, areaWrapper);

        PageResponse<StockScenicAreaDTO> pageResponse = new PageResponse<>(stockScenicAreaDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());

        return pageResponse;
    }



   private Long stockId;



    @Override
    public Result delete(StockScenicAreaPhotoDeleteReq stockScenicAreaPhotoDeleteReq, TokenUser currentUser){
        Integer delNum=0;
        for (StockScenicAreaPhotoReq req : stockScenicAreaPhotoDeleteReq.getIds()) {
            QueryWrapper<StockScenicAreaPhoto> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq( "id",req.getId());
            queryWrapper.eq("is_deleted",0);
            Integer count = stockScenicAreaPhotoMapper.selectCount(queryWrapper);
            if(count.equals(1)){
                StockScenicAreaPhoto stockScenicAreaPhoto=new StockScenicAreaPhoto();
                stockScenicAreaPhoto.setId(req.getId());
                stockScenicAreaPhoto.setIsDeleted(NumberConstant.ONE.getValue());
                if(stockScenicAreaPhotoMapper.updateById(stockScenicAreaPhoto)>0)
                    delNum++;
            }
//            if(count.equals(0)){
//                Result result = new Result();
//                result.setCode(SystemError.MAINDATA_4019.getCode());
//                result.setMsg(SystemError.MAINDATA_4019.getMsg());
//                return result;
//            }
        }
        return new Result(delNum);


    }

    @Override
    public List<OperationLogDTO> opeartionRecords(TokenUser currentUser){
        QueryWrapper<OperationLog> queryWrapper=new QueryWrapper();
        queryWrapper.like("title","景点资料");
        queryWrapper.like("description","景点资料");
        queryWrapper.eq("type","ADD").or();
        queryWrapper.eq("type","UPDATE").or();
        queryWrapper.eq("type","DELETE");
        List<OperationLog> operationLogList=operationLogMapper.selectList(queryWrapper);
        List<OperationLogDTO> operationLogDTOList=new ArrayList<>();
        operationLogList.forEach( log->{
            OperationLogDTO operationLogDTO=EntityUtil.copy(log,OperationLogDTO.class);
            operationLogDTOList.add(operationLogDTO);
        });
        return  operationLogDTOList;
    }

    /**
     * 新增图片库
     *
     * @param req 新增图片库入参
     * @param id 当前登录人id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<List<StockScenicAreaPhotoDTO>> addPhoto(StockScenicAreaPhotoBatchAddReq req, Long id) {
        List<StockScenicAreaPhotoDTO> photoDTOList = new ArrayList<>();
        StockScenicArea scenicArea = EntityUtil.copy(req, StockScenicArea.class);
        long areaId = SnowflakeIdWorker.nextId();
        scenicArea.setId(areaId);
        scenicArea.setCreateId(id);
        LocalDateTime nowTime = LocalDateTime.now();
        scenicArea.setGmtCreate(nowTime);
        scenicArea.setIsDeleted(0);
        stockScenicAreaMapper.insert(scenicArea);
        // 图片库
        List<StockScenicAreaPhotoReq> imgS = req.getImgList();
        if(CollectionUtils.isNotEmpty(imgS)){
            List<StockScenicAreaPhoto> photos = EntityUtil.copyList(imgS, StockScenicAreaPhoto.class);
            for (StockScenicAreaPhoto photo : photos) {
                Long photoId = SnowflakeIdWorker.nextId();
                StockScenicAreaPhotoDTO stockScenicAreaPhotoDTO = new StockScenicAreaPhotoDTO();
                stockScenicAreaPhotoDTO.setId(photoId);
                stockScenicAreaPhotoDTO.setTitle(photo.getTitle());
                photo.setId(photoId);
                photo.setIsDeleted(0);
                photo.setStockId(areaId);
                photo.setCreateId(id);
                photo.setGmtCreate(nowTime);
                photoDTOList.add(stockScenicAreaPhotoDTO);
            }
            // 批量插入图片
            stockScenicAreaPhotoMapper.insertBatchSomeColumn(photos);
        }
        return Result.success(photoDTOList);
    }

    /**
     * 根据图片id查询图片
     *
     * @param id 图片id
     * @return 返回值
     */
    @Override
    public StockScenicAreaPhotoDTO queryPhoto(Long id) {
        StockScenicAreaPhoto photo = stockScenicAreaPhotoMapper.selectById(id);
        StockScenicAreaPhotoDTO scenicAreaPhotoDTO = EntityUtil.copy(photo, StockScenicAreaPhotoDTO.class);
        return scenicAreaPhotoDTO;
    }

    /**
     * 根据地区id或名称查询图片
     *
     * @param stockScenicAreaPhotoListReq 入参
     * @return 所有图片
     */
    @Override
    public PageResponse<StockScenicAreaPhotoDTO> areaPhoto(StockScenicAreaPhotoListReq stockScenicAreaPhotoListReq) {
        IPage<StockScenicAreaPhotoDTO> page = new Page<>(stockScenicAreaPhotoListReq.getPageNo(),stockScenicAreaPhotoListReq.getPageSize());
        page = stockScenicAreaPhotoMapper.queryList(stockScenicAreaPhotoListReq,page);
        PageResponse<StockScenicAreaPhotoDTO> result = new PageResponse<>(page.getRecords(),page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }


}

